package PangController;


import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.util.ArrayList;

/**
 * Created by baraaorabi on 5/1/15.
 */
public class GameEngine {

    private static final int FINAL_LEVEL = 5;
    private ArrayList<ArrayList> gameObjects;

    public boolean isPaused() {
        return paused;
    }

    private boolean paused = false;



    double remainingTime = 9999999;
    double tickPace;
    private int score;
    private int currentLevel;
    MapEngine mapEngine;
    CollisionManager collisionManager;
    InputManager inputManager;



    public GameEngine (int level) {
        this.currentLevel = level;
        //this.tickPace = tickPace;
        resetLevel();
    }

    public ArrayList<ArrayList> getGameObjects() {
        return gameObjects;
    }

    public void pause(){
        paused = true;
    }

    public void resume(){
        paused = false;
    }

    public void tick() throws GameOverException {

        if (!paused){
            try {
                //inputManager.applyKeyEvents();
                collisionManager.checkCollisions(gameObjects);
            } catch (HeroDiedException e) {
                if (!mapEngine.decrementHeroLives()){
                    resetLevel();
                    e.printStackTrace();
                } else {
                    e.printStackTrace();
                    //String str = ""+gameObjects.get(1).size();
                    throw new GameOverException();
                }
                e.printStackTrace();
            }

            remainingTime -= tickPace;

            if (remainingTime < 0){
                if (!mapEngine.decrementHeroLives()){
                    resetLevel();
                } else
                {
                    throw new GameOverException();
                }
            }
        }
    }

    public void notifyWin(){
        if (!(currentLevel == FINAL_LEVEL)){
            currentLevel++;
            resetLevel();

        }
    }

    private void resetLevel() {
        collisionManager = new CollisionManager(this);
        mapEngine = new MapEngine();
        inputManager = new InputManager(mapEngine, this);

        mapEngine.setLevel(currentLevel);
        gameObjects = mapEngine.getGameObjects();

    }


    public void incrementScore(int score){
        this.score += score;
    }

    public void incrementTime(double addtionalTime) {
        this.remainingTime += addtionalTime;
    }

    public int getScore() {
        return score;
    }

    public void drawObjects(Graphics page) {
        mapEngine.drawObjects(page);
    }

    public void detectInput(KeyEvent e) {
        inputManager.detectInput(e);
    }

    public void moveHero(int dir)
    {
        mapEngine.moveHero(dir);
    }

    public void shoot(){mapEngine.shoot();}
}
